<template>
	<div class="app-container">
		<el-row>
			<el-col :span="24">
				<el-row class="mb10">
					<el-form v-model="queryParams" ref="queryForm" :inline="true" label-width="80px">
						<el-form-item v-for="item in queryFields" :key="item.id" :label="item.label">
							<el-input v-if="item.queryOptions.type == 'text'" v-model="queryParams[item.prop]" :placeholder="item.queryOptions.placeholder" clearable size="small" />
							<el-select v-if="item.queryOptions.type == 'select'" v-model="queryParams[item.prop]" clearable>
								<el-option v-for="it in qOptions" :key="it.value" :value="it.value" :label="it.label"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
							<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
						</el-form-item>
					</el-form>
				</el-row>
				<el-row :gutter="20" class="mb8">
					<el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handlerAdd" v-hasPermi="['system:user:add']">添加</el-button></el-col>
					<el-col :span="1.5">
						<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']">删除</el-button>
					</el-col>
				</el-row>
				<i-table :columns="columns" :list="list"  :options="options" @handleSelectionChange="handleSelectionChange">
					<el-table-column slot="operate" label="操作" align="center">
						<template slot-scope="scope">
<!--              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleSetRole(scope.row)" v-hasPermi="['system:user:set_role']">设置角色</el-button>-->
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleSetRole(scope.row)" >设置角色</el-button>
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">修改</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
						</template>
					</el-table-column>
				</i-table>

				<pagination v-show="total > 0" :total="total" :page.sync="pageParams.pageNum" :limit.sync="pageParams.pageSize" @pagination="getList" />
			</el-col>
		</el-row>
		<el-dialog v-dialog-drag :visible.sync="open" :title="title" :close-on-click-modal="false">
			<common-form ref="myForm" :fields="formFields" :form="myForm"></common-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm" size="small">确 定</el-button>
				<el-button @click="cancel" size="small">取 消</el-button>
			</div>
		</el-dialog>
    <el-dialog v-dialog-drag :visible.sync="setRoleSwich" title="设置角色" :close-on-click-modal="false">
      <el-form rel="roleForm" :model="setRoleForm" label-width="120px" label-suffix=":">
<!--        <el-form-item label="账号">-->
<!--          <el-input v-model="setRoleForm.account" disabled />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="姓名">-->
<!--          <el-input v-model="setRoleForm.name" disabled />-->
<!--        </el-form-item>-->

        <el-form-item label="角色">
          <el-checkbox-group v-model="setRoleForm.roles" >
            <el-checkbox v-for="item in roleOptions" :key="item.id" :label="item.id" >{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRoleForm" size="small">确 定</el-button>
        <el-button @click="cancelRoleForm" size="small">取 消</el-button>
      </div>
    </el-dialog>
	</div>
</template>

<script>
import { listUser, addUser, updateUser, delUser, updateUserOrigin,oneUserForEdit,oneUserOrigin } from '@/api/system/user.js';
import { requestByUrl } from '@/utils/tools';
import tableConf from './conf/tableConf.js';
import formConf from './conf/formConf.js';
import { isNull } from '@/utils';
export default {
	name: "User",
	data() {
		return {
			ids: [],
			total: 0,
			multiple: true,
			queryParams: {},
			open: false,
      setRoleSwich:false,
			pageParams: {
				pageNum: 1, // 页码
				pageSize: 10 // 单页条数
			},
			list: [],
			queryFields: [],
			options: {
				height: 630,
				mutiSelect:true
			},
			title: '',
			formFields: [],
			myForm: {},
			qOptions: {},
      setRoleForm:{
			  id:undefined,
        roles: undefined
      },
      roleOptions:[],
      columns: this._.cloneDeep(tableConf.fields)
		};
	},
	created() {
		this.getList();
		this.initData();
	},
	computed: {
	  /*
		columns() {
			let cols = [];
      cols = tableConf.fields
			cols.push({
				slot: 'operate',
				isQueryField: false
			});
			return cols;
		}

	   */
	},
	methods: {
		initData() {
			this.queryFields = tableConf.fields.filter(element => {
				// element.placeholder = `请输入${element.label}`;
				return element.isQueryField;
			});
			this.queryFields.map(item => {
				// setObjectField(this, item.queryOptions.type, this.queryParams, item.prop, item.queryOptions.value);
				this.$set(this.queryParams, item.prop, item.queryOptions.value);
				if (item.queryOptions.type == 'select') {
					if (item.queryOptions.options.t == 'local') {
						this.$set(this.qOptions, item.prop, item.queryOptions.options.values);
					} else {
						let list = [];
						requestByUrl(item.queryOptions.options.values).then(res => {
							res.data.lists.map(i => {
								list.push({
									label: i.name,
									value: i.id
								});
							});
							this.$set(this.options, item.prop, list);
						});
					}
				}
			});

      this.formFields = formConf.fields.map(it => {
			  let rules = []
        let mergeRules = []
			  if (it.required) {
			    rules.push({
            required:true,
            message: it.message ? it.message : it.placeholder,
            trigger: it.trigger ? it.trigger : 'blur'
          })
        }
			  if (it.rules) {
          mergeRules = mergeRules.concat(rules).concat(it.rules)
        }  else {
          mergeRules = rules
        }
			  it['rules'] = mergeRules
				this.$set(this.myForm, it.prop, it.defaultValue);
			  return it
			});
      // this.formFields = formConf.fields;
		},
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id);
			this.multiple = !selection.length;
		},
		handlerAdd() {
			this.reset();
			this.open = true;
			this.title = '添加';
		},
		handleUpdate(row) {
			let vm = this;
			const id = row.id;
			this.reset();
			this.open = true;
			this.title = '修改';
      oneUserForEdit(id).then(response => {
				let f = response.data;
				Object.keys(f).forEach(key => {
					if (typeof f[key] == 'object' && f[key] != null) {
						if (f[key] instanceof Array) {
							let temp = [];
							f[key].map(i => {
							  if (typeof i == 'number') {
							    temp.push(i)
                } else if (typeof i == 'object') {
                  temp.push(i.id);
                }
							});
							vm.$set(vm.myForm, key, temp);
						} else {
							vm.$set(vm.myForm, key, f[key].id);
						}
					} else {
						vm.$set(vm.myForm, key, f[key]);
					}
				});
			});
		},
		handleDelete(row) {
			const ids = row.id != undefined ? [row.id] : this.ids;

			this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
					let data = {
						ids: ids
					};
					return delUser(data);
				})
				.then(() => {
					this.getList();
					this.msgSuccess('删除成功');
				})
				.catch(() => {});
		},
		handleQuery() {
			this.pageParams.pageNum = 1;
			this.getList();
		},
		resetQuery() {
			this.resetForm('queryForm');
			this.queryFields.map(item => {
				this.queryParams[item.prop] = item.queryOptions.value;
			});
			this.handleQuery();
		},
		getList() {
			let data = {
				page: this.pageParams.pageNum,
				limit: this.pageParams.pageSize,
				_order: ['id']
			};
			let w = {};
			this.queryFields.forEach(ele => {
				let key = '';
				if (!isNull(this.queryParams[ele.prop])) {
					if (ele.queryOptions.type == 'text') {
						key = ele.prop + '__icontains';
						w[key] = this.queryParams[ele.prop];
					}
				}
			});
			if (Object.keys(w).length > 0) {
				data['_where'] = w;
			}
			listUser(data).then(response => {
				this.list = response.data.lists;
				this.total = response.data.query.total;
			});
		},
		submitForm() {
      this.$refs['myForm'].validate(()=>{
        if (this.myForm.id != undefined) {
          updateUser(this.myForm).then(response => {
            this.msgSuccess('修改成功');
            this.open = false;
            this.getList();
          });
        } else {
          addUser(this.myForm).then(response => {
            this.msgSuccess('新增成功');
            this.open = false;
            this.getList();
          });
        }
      })
		},
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			formConf.fields.map(it => {
				this.myForm[it.prop] = it.defaultValue;
			});
			if (this.myForm['id'] != undefined) {
				this.myForm['id'] = undefined;
			}
			// this.$refs['myForm'].resetForm()
			this.resetForm('form');
		},
    // 给用户设置角色
    handleSetRole(row) {
      this.setRoleSwich = true
      const id = row.id;
      this.setRoleForm.id = id
      // this.setRoleForm =
      requestByUrl("/admin/HtRole/list", 'post').then(res=>{
        this.roleOptions = res.data.lists
      })
      oneUserForEdit(id).then(response => {
        // this.setRoleForm.roles = response.data.roles
        this.setRoleForm = response.data
      })
    },
    submitRoleForm() {
      updateUser(this.setRoleForm).then(response=>{
        this.msgSuccess('角色设置成功！');
        this.setRoleSwich = false;
        this.getList();
      })
    },
    cancelRoleForm() {
		  this.setRoleSwich = false;
      this.resetForm('roleForm');
      this.setRoleForm.roles = undefined;
      this.setRoleForm.id = undefined
    }
	}
};
</script>

<style lang="sass" scoped></style>
